const {User, UserInfo} = require('../db/model/index')
const {Op} = require('sequelize')

const getUser = async (userName, password) => {
  const whereOpt = {
    userName
  }

  if (password) {
    whereOpt.password = password
  }

  const result = await User.findOne({
    attributes: {exclude: [ 'password' ]},
    where: whereOpt,
    include: [ {
      model: UserInfo
    } ]
  })

  return result ? result.dataValues : result
}

const createUser = async ({userName, password, nickName = userName}) => {
  const result = await User.create({
    userName,
    password,
    nickName
  })

  const data = result.dataValues

  return data
}

const updateUser = async (updateData, whereData) => {
  const result = await User.update(updateData, {
    where: whereData
  })
  return result[0] > 0
}

const getUserList = async ({userName, nickName, pageIndex, pageSize, createTime}) => {
  const where = {
    nickName: {
      [Op.substring]: nickName
    },
    userName: {
      [Op.substring]: userName
    }
  }

  if (createTime.length) {
    where[`created_at`] = {
      [Op.gte]: createTime[0],
      [Op.lte]: createTime[1]
    }
  }

  const result = await User.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    attributes: {
      exclude: [ 'password' ]
    },
    where
  })

  return {
    count: result.count,
    data: result.rows
  }
}

module.exports = {
  getUser,
  createUser,
  updateUser,
  getUserList
}
